package com.myshiro.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myshiro.pojo.User;
import com.myshiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author Jane
 * @date 2024-06-14 14:21
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping("/doLogin")
    public String doLogin(@RequestParam("usrname") String usrname
                          , @RequestParam("usrpassword") String usrpassword
                          , Model model
                          , HttpSession session
                          ){
        String msg="";

        try {
            //usrpassword =userService.encryptPassword(usrpassword);//  ...883e

            UsernamePasswordToken token = new UsernamePasswordToken(usrname,usrpassword);  //明文

            Subject currentUser = SecurityUtils.getSubject();
//            token.setRememberMe(true);//记住我
            currentUser.login(token);//登录

            //认证成功
            User user = (User) currentUser.getPrincipal();

            session.setAttribute("loginUser",user);

            return "index";
        }catch (UnknownAccountException e){
            msg="账户不存在";
        }catch (LockedAccountException e){
            msg="账户已经被锁定";
        }catch (AuthenticationException e) {
            msg="密码错误";
            e.printStackTrace();
        }catch (Exception e){
            msg="登录失败:"+e.getMessage();
        }

        model.addAttribute("msg",msg);

        return "/login";

    }

    @RequestMapping("/list")
    public String list(){
        return "/user/list";
    }

    @RequestMapping("/update")
    @RequiresPermissions("用户修改")
    public String update(){
        return "/user/update";
    }

    @RequiresRoles("管理员_玖谊")
    @RequestMapping("/add")
    public String add(){
        return "/user/add";
    }



    @RequestMapping("/del")
    public String del(){
        return "/user/del";
    }


    @RequestMapping("/logout")
    public String logout(HttpSession session){

        if (null != session.getAttribute("loginUser")){
            session.removeAttribute("loginUser");
        }
        SecurityUtils.getSubject().logout();//shiro的注销方法
        return "redirect:/toLogin";
    }
}
